//import '/pages/tabbar-template/tabbar-template';

var app = getApp(); 
Page({
  
  /**  
   * 页面的初始数据 
   */
  data: {
    scrollTop:0,
    tabbarIndex: 0,
    tabbar: [
      {
        img: 'https://crm.bxwhl.com/static/tabbar/index.png',
        imgSelect: 'https://crm.bxwhl.com/static/tabbar/index-select.png',
        text: '名片',
        url: '/pages/index/index',
      },
      {
        img: 'https://crm.bxwhl.com/static/tabbar/goods.png',
        imgSelect: 'https://crm.bxwhl.com/static/tabbar/goods-select.png',
        text: '产品',
        url: '/pages/product/product',
      },
      {
        img: 'https://crm.bxwhl.com/static/tabbar/dynamic.png',
        imgSelect: 'https://crm.bxwhl.com/static/tabbar/dynamic-select.png',
        text: '动态',
        url: '/pages/dynamic/dynamic',
      },
      {
        img: 'https://crm.bxwhl.com/static/tabbar/website.png',
        imgSelect: 'https://crm.bxwhl.com/static/tabbar/website-select.png',
        text: '官网',
        url: '/pages/website/website',
      },
       {
        img: 'https://crm.bxwhl.com/static/tabbar/mine.png',
        imgSelect: 'https://crm.bxwhl.com/static/tabbar/mine-select.png',
        text: '我',
        url: '/pages/mine/mine',
      },
    ],
    hello:'你好',
      // 消息条数
    noteNum: 0,
    // 个人详情是否显示
    showDetail: true,
    // 阅读百分比
    readPercent: 0,
    // 生成卡片
    actionSheetHidden:true,
    // 预览二维码
    previewShow: false,
    maskShow: false,
    index_coupon_show: false,
    index_coupon_get_show: false,
  },
  showCoupon:function(){
    var coupon = this.data.coupon;
    if(coupon.is_haved == 1){
      this.setData({
        maskShow: true,
        index_coupon_get_show: true,
      })
    }else{
      this.setData({
        maskShow: true,
        index_coupon_show: true,
      })
    }
    
  },
  closeCoupon:function(){
    this.setData({
      maskShow: false,
      index_coupon_show: false,
    })
  },
  closeGetCoupon:function(){
    this.setData({
      maskShow: false,
      index_coupon_get_show: false,
    })
  },
  maskHide:function(){
    this.setData({
      maskShow: false,
      index_coupon_show: false,
    })
  },
  completemessage:function(e){
    if (e.detail.errcode == 0){
      wx.showModal({
        title: '已将你的联系方式通过服务通知发送给你，请在微信消息列表查看',
        showCancel: false,
        confirmText: '我知道了'
      })
    } else if ( e.detail.errcode == -3006){
      wx.showModal({
        title: '你们已经是好友了',
        showCancel: false,
        confirmText: '我知道了'
      })
    }
    app.userBehavior(108,'企业微信添加好友')
  },
  // 预览二维码
  previewCardCode:function(){
    var qrcode = this.data.detail.qrcode;
    this.setData({
      previewCode: qrcode,
      previewShow:true,
    })
  },
  previewHide:function(){
    this.setData({
      previewShow: false,
    })
  },
  // 打电话 
  makePhoneCall: function (e) {
    var phone = e.currentTarget.dataset.text;
    app.userBehavior(102,'拨打了你的电话')
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },
  // 显示详情
  showDetail:function(){
    var that = this;
    var showDetail = that.data.showDetail;
    if (showDetail == true){
      showDetail = false;
    }
    else{
      showDetail = true;
    }
    that.setData({
      showDetail: showDetail,
    })
  },
  // 点击靠谱
  tozan:function(){
    var that = this;
    var params = {
      status : that.data.detail.is_reliable ? 0 : 1
    };
    app.httpRequest('card.card/reliable', params, 'get', true, function(res){
      that.setData({
        'detail.reliable' : that.data.detail.is_reliable ? --that.data.detail.reliable :  ++that.data.detail.reliable,
        'detail.is_reliable' : !that.data.detail.is_reliable,
      })
      app.userBehavior(that.data.detail.is_reliable ? 105 : 106,'进行了靠谱操作')
    })
  },

  // 点击分享
  actionSheetTap: function () {
    var that = this;
    var userInfo = wx.getStorageSync('userInfo')
    if(userInfo){
      that.setData({
        actionSheetHidden: !that.data.actionSheetHidden
      })
    }else{
      wx.navigateTo({
        url: "/pages/welcome/welcome",
      })
    }
  },
  actionSheetbindchange: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },
  bindMenu1: function () {
    this.setData({
      menu: 1,
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },
  bindMenu2: function (e) {
    var qrcode = this.data.detail.qrcode;
    this.setData({
      previewCode: qrcode,
      previewShow:true,
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },
  // 复制信息
  copyText:function(e){
    var that = this;
    var copyText = e.currentTarget.dataset.text;
    var name =e.currentTarget.dataset.name;
    wx.setClipboardData({
      data: copyText,
      success(res) {
        wx.getClipboardData({
          success(res) {
          }
        })
      }
    })
    app.userBehavior(104,'复制个人信息：'+copyText)
  },
  // 打开位置
  openLocation:function(){
    var that = this;
    var latitude = parseFloat(that.data.enterprise.latitude);
    var longitude = parseFloat(that.data.enterprise.longitude);
    app.userBehavior(103,'查看了公司地址')
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      name:that.data.enterprise.name,
      address:that.data.enterprise.detail,
      scale: 14,
    })
  },
  // 添加通讯录
  addPhoneContact:function(e){
    var that = this;
    var user = that.data.detail;
    var enterprise = that.data.enterprise;
    app.userBehavior(107,'保存通讯录')
    wx.addPhoneContact({
      firstName:         user.real_name,
      photoFilePath:     user.avatarUrl,
      nickName:          user.real_name,
      mobilePhoneNumber: user.mobile,
      weChatNumber:      user.weixin,
      organization:      enterprise.name,
      title:             user.position,
      workPhoneNumber:   user.mobile,
      email:             user.email,
      homeAddressCity:    enterprise.detail,
    })
  },
  // 标签点击
  tipsZan:function(e){
    var that = this;
    var index = e.currentTarget.dataset.index;
    var id = e.currentTarget.dataset.id;
    var tag = that.data.detail.tag;
    var hasZan = tag[index].hasZan;
    if(hasZan == true){
      tag[index].hasZan = false;
      tag[index].num--;
    }else{
      tag[index].hasZan = true;
      tag[index].num++;
    }
    app.httpRequest('card.card/tagStatus', {tag_id: id,status: hasZan ? 0 : 1}, 'get', false, function(res){
      that.setData({
        'detail.tag':tag,
      })
      app.userBehavior(hasZan ? 109 : 110,'进行了个人标签点赞操作')
    })
    
  },
  toproductDetail:function(e){
    var that = this;
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/productDetail/productDetail?id='+id,
    })
  },
  toproduct:function(e){
    wx.navigateTo({
      url: '/pages/product/product',
    })
  },
  // 名片夹
  tomyCards:function(){
    var userInfo = wx.getStorageSync('userInfo')
    if(userInfo){
      wx.redirectTo({
        url: '/pages/myCards/myCards',
      })
    }else{
      wx.navigateTo({
        url: "/pages/welcome/welcome",
      })
    }
  },
  // 留言
  tochat:function(){
    wx.navigateTo({
      url: '/pages/chat/chat',
    })
  },
  getPhoneNumber: function (e) {
    var that = this;
    var iv = encodeURIComponent(e.detail.iv)
    var type = e.currentTarget.dataset.type || '';
    var encryptedData = encodeURIComponent(e.detail.encryptedData)
    wx.showLoading({
      title: '信息授权中',
    })
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      if(type == 'chat'){
        wx.navigateTo({
          url: '/pages/chat/chat',
        })
      }
      wx.hideLoading()
    } else {
      wx.request({
        url: app.siteInfo.siteroot + 'user/getPhone',
        method: "post",
        data: {
          iv: iv,
          encryptedData: encryptedData,
          token: wx.getStorageSync('token'),
          enterprise_id: app.siteInfo.enterprise_id,
        },
        success: function (res) {
          if(res.data.code == -1){
            wx.navigateTo({
              url: '/pages/welcome/welcome',
            })
            return;
          }
          if(res.data.code == 1){
            var user = wx.getStorageSync('userInfo');
            user.phone = res.data.data.phone;
            wx.setStorageSync('userInfo', user)
            that.setData({
              hasphone: true,
            })
            if(type == 'chat'){
              wx.navigateTo({
                url: '/pages/chat/chat',
              })
            }else if(type == 'save'){
              that.addPhoneContact();
            }else if(type == 'coupon'){
              that.getCoupon();
            }
          }
        },
        complete: function(){
          wx.hideLoading()
        }
      })
    }
  },
  getCoupon:function(){
    var coupon_id = this.data.coupon.coupon_id;
    var that = this;
    app.httpRequest('coupon/getCoupon', {coupon_id}, 'get', false, function(res){
      that.setData({
        index_coupon_show: false,
        index_coupon_get_show: true,
        'coupon.is_haved': 1
      })
      app.userBehavior(130,'领取了首页福利')
    })
    
  },
  // 滚动计算阅读
  scroll:function(e){
    var that = this;
    var scrollHeight = e.detail.scrollHeight;
    var scrollTop = e.detail.scrollTop;
    var windowHeight = that.data.windowHeight;
    var height = scrollHeight - windowHeight -20;
    var scrollPercent = (scrollTop/height) * 100;
    scrollPercent = Math.ceil(scrollPercent);
    var readPercent = that.data.readPercent;
    if (scrollPercent >100){
      scrollPercent = 100;
      readPercent = 100;
    }else{
      scrollPercent = scrollPercent;
      if (scrollPercent > readPercent){
        readPercent = scrollPercent;
      }else{
        readPercent = readPercent;
      }
    }
    that.setData({
      readPercent: readPercent 
    })
  },
  // tabbar跳转
  tabbarNav:function(e){
    var url = e.currentTarget.dataset.url;
    wx.redirectTo({
      url: url,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.card_id){
      wx.setStorageSync('share_card_id', options.card_id)
    }
    
  },
  gerCardInfo: function(){
    var that = this;
    app.httpRequest('card.card/detail', {}, 'get', false, function(res){
      res.data.enterprise.address = res.data.enterprise.detail;
      res.data.detail.emails = res.data.detail.email;
      that.setData({
        detail: res.data.detail,
        visit: res.data.visit,
        enterprise: res.data.enterprise,
        product: res.data.product,
        coupon: res.data.coupon,
        pageShow: true,
        hasphone: wx.getStorageSync('userInfo').phone || false,
        user: wx.getStorageSync('userInfo'),
        showTopMsg: app.siteInfo.is_first ? true : false,
        showTopMsgCss: app.siteInfo.is_first ? true : false,
      })
      wx.setStorageSync('share_card_id', res.data.detail.user_id)
      if(app.siteInfo.is_first){
        var hours = new Date().getHours();
        var hello = that.data.hello;
        if(hours > 6 && hours < 9){
          hello = '早上好';
        }else if(hours >= 9 && hours < 12){
          hello = '上午好';
        }else if(hours >= 12 && hours < 18){
          hello = '下午好';
        }else if(hours >= 18 && hours < 22){
          hello = '晚上好';
        }else if(hours >= 22 && hours < 24){
          hello = '深夜好';
        }else if(hours >= 0 && hours < 6){
          hello = '凌晨好';
        }
        that.setData({
          hello: hello,
        })
        app.siteInfo.is_first = 0;
        setTimeout(function(){
          that.setData({
            showTopMsgCss: false,
          })
        },4000)
        setTimeout(function(){
          that.setData({
            showTopMsg: false,
          })
        },5000)
      }
    })
  },

  // 处理滚动文字
  hbTextSet:function(){
    var that = this;
    var lhblist = that.data.lhblist;
    var hbLen = lhblist.length;
    var hbIndex = that.data.hbIndex;
    if (hbIndex < hbLen - 1) {
      hbIndex++
    } else {
      hbIndex = 0;
    }
    that.setData({
      hbIndex: hbIndex,
      lhbname: lhblist[hbIndex].wechat_name,
      lhbmoney: lhblist[hbIndex].deduct,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },
  changeAudio:function(){
    var that = this;
    if (that.data.audioPlay==true){
      that.audio.pause()
      that.setData({
        audioPlay: false
      })
    }else{
      that.audio.play()
      that.setData({
        audioPlay: true
      })
    }
  },
  setTime:function(e){
    var that = this;
    var min = Math.floor(e / 60);
    if (min < 10) {
      min = '0' + min
    }
    var sec = Math.floor(e % 60);
    that.setData({
      audioMin: min,
      audioSec: sec,
    })
  },  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.setData({
      startTime: new Date().getTime(),
      windowHeight: wx.getStorageSync('systemInfo').windowHeight,
    })
    that.gerCardInfo()
  },
  // 获得停留时间，毫秒级
  getStopTime:function(){
    var that = this;
    var endTime = new Date().getTime();
    var startTime = that.data.startTime;
    var stopTime = endTime - startTime;
    that.setData({
      stopTime: stopTime
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    that.getStopTime();
    var stoptime =  that.data.stopTime;
    var percent = that.data.readPercent;
    app.userBehavior(100,'访问了你的名片',stoptime,percent)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
    that.getStopTime();
    var stoptime =  that.data.stopTime;
    var percent = that.data.readPercent;
    app.userBehavior(100,'访问了你的名片',stoptime,percent)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let { scrollTop, enterprise, detail} = this.data
    this.setData({
      scrollTop:0
    }) 
    app.userBehavior(101,'转发名片给好友')
    return {
      title: '你好，我是'+enterprise.name+'的'+detail.position+'——'+detail.real_name+',很荣幸认识您！',
      path: "/pages/index/index?share_card_id=" + wx.getStorageSync('share_card_id') + "&share_user_id=" + wx.getStorageSync('user_id'),
      success: function (a) {
      },
      fail: function (a) { }
    };
  }
})